package com.gravata.enigma;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

import com.gravata.enigma.activities.TelaInicial;
import com.gravata.enigma.model.Bouquet;
import com.gravata.enigma.model.BouquetService;
import com.gravata.enigma.model.Regra;
import com.gravata.enigma.model.Service;

public class RegrasApplyer extends AsyncTask<Regra, String, Boolean> {

	private ProgressDialog progress;

	private  boolean alwaysReload=true;
	private  Regra exclude;
	private  Regra favorito;
	private Context context;
	private ReloadDataListener dataListener;
	private boolean limparAntes;
	public RegrasApplyer(Context context, boolean limparAntes,ReloadDataListener dataListener) {
		this.context=context;
		this.dataListener=dataListener;
		this.limparAntes=limparAntes;
	}

	@Override
	protected Boolean doInBackground(Regra... params) {
		if(params.length>0){
			Regra regra = params[0];
			apply(regra);
		}else
			applyAll();

		return true;
	}

	public void applyAll(){
		alwaysReload=false;
		for(Regra regra: TelaInicial.regras){
			if(!regra.isExclude())
				apply(regra);
		}
		applyExclude();
		TelaInicial.reloadBouquetData();
		dataListener.onReloadData();
		alwaysReload=true;
	}

	public void apply(Regra regra){
			Log.d("APLICAR PARA", regra.getName());
			Bouquet bouquet=TelaInicial.repositorioBouquets.porReference(regra.getReference(), TelaInicial.profile);

			if(limparAntes){
				if(bouquet!=null){
					if(bouquet.getServices().size()>0)
						bouquet.getServices().clear();
				}
			}
			//cria o bouquet caso ele nao exista
			if(bouquet==null){
				bouquet=new Bouquet();
				bouquet.setReference(regra.getReference());
				bouquet.setName(regra.getName());
				bouquet.setOrdem(regra.getOrdem());
				bouquet.setProfile(TelaInicial.profile);
				try {
					TelaInicial.repositorioBouquets.inserir(bouquet);
				} catch (SQLException e) {
					Log.e("REGRASAPPLYER", e.getMessage());
					return;
				}
			}

			//ForeignCollection<Filtro> filtros=regra.getFiltros();
			List<Service> canais= TelaInicial.servicos;

			List<Service> encontrados=new ArrayList<Service>();

			for(Service canal:canais){

				if(regra.atende(canal)){
					publishProgress(context.getString(R.string.aplicando_regra)+" "+regra.getName()+"...\n\n"+canal.getName()+": OK");
					encontrados.add(canal);
				}else{
					publishProgress(context.getString(R.string.aplicando_regra)+" "+regra.getName()+"...\n\n"+canal.getName()+": NO");
				}

			}

			Collections.sort(encontrados);
			int i=1;
			for(Service canal: encontrados){
				BouquetService bs=new BouquetService(bouquet, canal, i);

				try {
					TelaInicial.repositorioBouquetService.inserirOuAtualizar(bs);
					i++;
				} catch (SQLException e) {
				}
			}
			TelaInicial.repositorioBouquets.apagaVazios(TelaInicial.profile);
			if(alwaysReload){
				TelaInicial.reloadBouquetData();
				dataListener.onReloadData();
			}

	}

	private void applyExclude(){
		publishProgress(context.getString(R.string.aplicando_exclude));
		getExclude();
		List<BouquetService> encontrados=new ArrayList<BouquetService>();
		List<BouquetService> bouquetServices=TelaInicial.repositorioBouquetService.listar(TelaInicial.profile);
		for(BouquetService bs:bouquetServices){
			if(exclude.atende(bs.getService())){
				encontrados.add(bs);
			}
		}

		try {
			TelaInicial.repositorioBouquetService.excluir(encontrados);
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

	private Regra getExclude() {
		for(Regra regra: TelaInicial.regras){
			if(regra.isExclude()){
				exclude=regra;
				break;
			}
		}
		return exclude;
	}

	private Regra getFavorito() {
		for(Regra regra: TelaInicial.regras){
			if(regra.isFavorito()){
				favorito=regra;
				break;
			}
		}
		return favorito;
	}

	@Override
	protected void onPreExecute() {
		progress = new ProgressDialog((Activity) context);
		// Cria novo um ProgressDialogo e exibe
		progress.setMessage(context.getString(R.string.carregando));
		progress.setCancelable(false);
		progress.show();

	}

	@Override
	protected void onProgressUpdate(String... values) {
		// Atualiza mensagem
		if (progress != null)
			progress.setMessage(values[0]);
	}

	@Override
	protected void onPostExecute(Boolean result) {

		progress.dismiss();
	}

}
